package server

import (
	"encoding/json"
	"fmt"
	"net"
	"simple_game/app/libs/logger"
	"simple_game/app/server/actor"
	"simple_game/app/utils"
	"time"
)

type Player struct {
	Actor      *actor.Actor
	Server     *Server
	PlayerData *PlayerData
}

type PlayerData struct {
	UUid        int64
	LastLoginAt int64
}

func (p Player) Loader() {
	p.Actor.Loader()
}

func (p Player) Start() {
	// 注册到director
	actor.RegisterActor(p.Actor.Pid(), p)
	p.Actor.Start()
}

func (p Player) Stop() {
	// 持久化
	data := p.PlayerData
	marshal, _ := json.Marshal(data)
	_, err := utils.RedisClient.Set(utils.RCtx, p.PersistenceKey(), marshal, 0).Result()
	if err != nil {
		logger.ERROR("actorId:", p.Actor.Name(), "	persistence fail", err)
	} else {
		logger.INFO("actorId:", p.Actor.Name(), "	persistence success")
	}
}

func (p Player) PlayerSend2Mail(msg []byte) {
	if len(msg) == 0 {
		return
	}
	if err := p.Actor.SendMail(msg); err != nil {
		logger.ERROR("send2Mail error,actorId:", p.Actor.Pid(), "err:", err)
	}
}

func (p Player) PersistenceKey() string {
	return fmt.Sprintf("player_data_%d", p.Actor.Pid())
}

func StartNewPlayerActor(conn net.Conn, s *Server) (Player, error) {
	uuid := utils.NewUid()
	playerActor := Player{
		Actor:  actor.NewActor(uuid, conn),
		Server: s,
		PlayerData: &PlayerData{
			UUid:        uuid,
			LastLoginAt: time.Now().Unix(),
		},
	}
	playerActor.Start()
	return playerActor, nil
}
